package likouJava;


import java.util.HashMap;
import java.util.Map;

public class 随机链表的复制 {
    public Node copyRandomList(Node head) {
        if(head == null)return null;

        //用一个哈希表来存储 原来节点和新节点的映射关系
        Map<Node, Node> map = new HashMap<>();

        //第一遍遍历，复制所有节点(只复制val)
        Node cur = head;
        while (cur != null){
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }

        //第二次遍历，复制next 和 random 指针
        cur = head;
        while (cur != null){
            Node newNode = map.get(cur);
            newNode.next = map.get(cur.next);
            newNode.random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }


}
